const dao = require("../Dao/Dao.js");
const { Op } = require("sequelize")
const { guanqAC, newsAC } = require("../utils/accessControl")
const { handleUpdate } = require("../utils/updateResp")

let d = new Date();
let nowTime = `${d.getMonth() + 1}-${d.getDate()} ${d.getHours()}-${d.getMinutes()}-${d.getSeconds()} `;
module.exports = {
  async getMyMessage(req, resp) {
    let where = { where: { [Op.or]: [{ fromid: req.query.uId }, { writerid: req.query.uId }] } }
    let data = await (req.query.isNews ? database.news : database.guanq).findAll(where)
    resp.send(data);
  },

  async getQ(req, resp) {
    let id = req.query.id;
    let qInfo = await database.guanq.findOne({ where: { id } })
    if (!qInfo) {
      resp.send({ code: -1 });
      return
    }
    let writerid = qInfo.writerid

    let uInfo = await database.user.findOne({ where: { id: writerid } })
    qInfo.dataValues.writer = uInfo.dataValues
    resp.send(qInfo);
  },

  async getNews(req, resp) {
    let id = req.query.id;
    resp.send(await database.news.findAll({ where: { id } }));
  },

  async setWrite(req, resp) {
    if (!(req.query.id && req.query.setWrite)) { resp.send({ code: -2 }); return; }
    let where = { id: req.query.id }, select = { writerid: req.query.setWrite }
    let data = req.query.isNews ? await database.news.update(select, { where }) : await database.guanq.update(select, { where })
    resp.send({ code: handleUpdate(data) });
  },

  async upQ(req, resp) {
    let ac = await guanqAC(req.query.id, req.query.uId)
    if (!ac.length) { resp.send({ code: -2 }); return; }
    let data = await database.guanq.update({ message: req.body.message, uptime: nowTime }, { id: req.query.id })
    resp.send({ code: handleUpdate(data) })
  },

  async upNews(req, resp) {
    let ac = await newsAC(req.query.id, req.query.uId)
    if (!ac.length) { resp.send({ code: -2 }); return; }
    let data = await database.news.update({ message: req.body.message, uptime: nowTime }, { id: req.query.id })
    resp.send({ code: handleUpdate(data) })
  },
  getCanUp(req, resp) {
    let param = [req.query["pid"], req.query["workid"]];
    let sql = `SELECT * FROM \`guanq\` WHERE  writerid = ? and id=?`;
    dao.do(sql, param, req.query["timer"], function (err, data) {
      resp.send(data);
      err ? console.log(err) : null;
    });
  },
  async setQImg(req, resp) {
    let data = await database.guanq.update({ imgurls: req.body.imgurls }, { where: { id: req.query.id } })
    resp.send({ code: handleUpdate(data) })
  },
  async create(req, resp) {
    let { id, fromid } = req.query
    let TEMP = { id, fromid, uptime: nowTime, url: '' }
    let data = req.query["isNews"] ? await database.guanq.create(TEMP) : await database.guanq.create(TEMP)
    resp.send({ code: handleUpdate(data) });
  },
  face(req, resp) {
    resp.sendfile("qqface/" + req.params.faceid + ".gif");
  },
  psd(req, resp) {
    resp.sendfile("psd/" + req.params.psdid + ".psd");
  },
};
